﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace ZHello.Net
{
    public class MTcpClient
    {
        public const int DefaultPort = 20210;

        private TcpClient _client;
        private NetworkStream sendStream;
        public string ServerIP { get; set; }
        public int ServerPort { get; set; }

        public void Connect(string ip, int port = DefaultPort)
        {
            ServerIP = ip;
            ServerPort = port;
            _client = new TcpClient();
            _client.Connect(ServerIP, ServerPort);
            sendStream = _client.GetStream();
        }

        public void Disconnect()
        {
            _client.Close();
            _client = null;
        }

        public void Dispose()
        {
            if (_client != null)
                _client.Close();
        }

        public bool SendData(string value)
        {
            if (value == null)
                return false;
            if (_client == null || !_client.Connected)
                return false;
            try
            {
                string str = value;
                Byte[] sendBytes = Encoding.Default.GetBytes(str);
                sendStream.Write(sendBytes, 0, sendBytes.Length);
                sendStream.Flush();
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}
